package rgbos.forum.domain;
import java.io.IOException;
import java.util.logging.*;

/**
 * @author  Ofir Dagan
 *
 */
public class Auditor {
	
	/** the logger*/
	private static Logger logger_;
	/** the handler */
	/**
	 * Constructor
	 * 
	 * @param logfile the log file name
	 */
	private static void AuditorSet(String logfile){
		Handler fh = null;
		logger_ = Logger.getLogger("Forum Logger");
		try{
			fh = new FileHandler(logfile);
			//fh.setFormatter(new java.util.logging.XMLFormatter());
			//fh.setFormatter(new java.util.logging.SimpleFormatter());
			
		fh.setFormatter(new Formatter() {
		         public String format(LogRecord rec) {
		             StringBuffer buf = new StringBuffer(1000);
		             buf.append(new java.util.Date());
		             buf.append(' ');
		             buf.append(rec.getLevel());
		             buf.append(':');
		             buf.append('\n');
		             buf.append('\t');
		             buf.append(formatMessage(rec));
		             buf.append('\n');
		             return buf.toString();
		             }
		           });

			}catch(IOException e){}
		logger_.setLevel(Level.FINEST);
		logger_.addHandler(fh);
		

	}
	/**
	 * @return the logger_ 
	 */
	public static Logger getLogger(String className) {
		return logger_;
	}
	
	/**
	 * 
	 * @param str to write in the log
	 */
	public  static synchronized void Log(String str,Class<?> c){
	//	System.out.println(str);   
		if(logger_==null){
			AuditorSet("log.txt");
		}
		try {		     
		      logger_.info(c.getName()+": "+str);
		   } catch (Exception e){
			   System.err.print("Couldn't log string! (" + e.getMessage() + ")");
		   } 		 
	}	
	/**
	 * 
	 * @param str to write in the log
	 */
	public static synchronized void Log(String str,String priorty,Class<?> c){
		if(logger_==null){
			AuditorSet("log.txt");
		}			//System.out.println(str);
		   try {
			   if(priorty.equalsIgnoreCase("finer")){
				   logger_.finer(c.getName()+": "+str);
			   }else if(priorty.equalsIgnoreCase("info")){
				   logger_.info(c.getName()+": "+str);
			   }else if(priorty.equalsIgnoreCase("fine")){
				   logger_.fine(c.getName()+": "+str);
			   }else if(priorty.equalsIgnoreCase("finest")){
				   logger_.finest(c.getName()+": "+str);
			   }else if(priorty.equalsIgnoreCase("severe")){
				   logger_.severe(c.getName()+": "+str);
			   }else{
				   System.err.println("No such level incident didn't log");
			   }
			   
		   } catch (Exception e){System.exit(1);} 
	}
	
}
